package com.bountytask.service.impl;
import com.bountytask.dao.ProveImageDao;
import com.bountytask.entity.ImageAndId;
import com.bountytask.entity.ProveImage;
import com.bountytask.service.ProveImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class ProveImageServiceImpl implements ProveImageService {
    @Autowired
    private ProveImageDao proveImageDao;

    @Value("${uploadPathImg}")
    private String uploadPathImg;

    //提交证明图片
    public long addImage(long userId,long taskId,String image){
        ProveImage proveImage = new ProveImage();
        proveImage.setImage(image);
        proveImage.setTaskId(taskId);
        proveImage.setUserId(userId);
        if (proveImageDao.addImage(proveImage)!=1)
            return -1;
        return proveImage.getId();
    }

    /**
     * 删除证明图片
     */
    public int deleteProve(long id){
        String imagePath=uploadPathImg+proveImageDao.selectUrl(id).substring(12);
        File deleteImg = new File(imagePath);
        if (deleteImg.delete())
            log.info("服务器图片删除成功");
        else {
            log.info("服务器图片删除失败");
            return 400;
        }
        proveImageDao.deleteProve(id);
        return 200;
    }

    /**
     * 查找该用户在该任务中提交的证明图片
     * @param userid
     * @param taskid
     * @return
     */
    public List<ImageAndId> selectImage(long userid, long taskid){
        HashMap<String,Object> map=new HashMap<>();
        map.put("userid",userid);
        map.put("taskid",taskid);
        return proveImageDao.selectImage(map);
    }

    /**
     * 批量删除证明图片
     * @param ids
     * @return
     */
    @Transactional
    public int _mDelete(List<Long> ids){
        List<Long> list=proveImageDao.selectById(ids);
        log.info(list.toString());
        if(list.size()!=ids.size()) return 400;
        List<String> paths=proveImageDao.selectUrlByIds(ids);
        for (int i = 0; i < paths.size(); i++){
            File imageFile=new File(uploadPathImg+paths.get(i).substring(12));
            if (!imageFile.delete())
                log.info("图片:"+paths.get(i)+"删除失败!");
        }

        if (proveImageDao._mDelete(ids)!=ids.size())
        {
            return 400;
        }
        return 200;
    }
}
